<?php
class Admin_Form_Users extends TBB_Form {
	
	public function init() {
		///////////////////// add path to custom validators  /////////////////////
		$this->addElementPrefixPath ( 'TBB_Validate', 'TBB/Validate/', 'validate' );
		
		// set attributes for main form
		$this->addAttribs(array(
			'class' => 'span-14',
			//'style' => 'background-color: #ccc;'
		));
		
		///////////////////// create id element  /////////////////////
		$id = $this->_createUserIDElement();		
		
		///////////////////// create username element  /////////////////////
		$username = $this->_createUsernameElement();
		
		///////////////////// create password element  /////////////////////	
		$password = $this->_createPasswordElement();   	
		
		///////////////////// create password confirmation /////////////////////
		$passwordConfirm = $this->_createPasswordConfirmElement();										      	
		
		///////////////////// create submit button  /////////////////////
		$submit = $this->_createSubmitButton();	
		
		// add all elements
		$this->addElements(array($id, $username, $password, $passwordConfirm, $submit));
		$this->addDisplayGroup(array('user_id', 'newUsername', 'password', 'password_confirm', 'submit'),
							  'userGroup',
							  array('class' => 'fieldsetForm span-7')
		);
		
		// set decorators for form
		$this->setDecorators($this->_formDecorators);
		$this->setDisplayGroupDecorators($this->_displayGroupDecorators);
	}
	
	public function disableRequiredOnPassword()
	{
		$this->getElement('password')->setRequired(false);
		$this->getElement('password_confirm')->setRequired(false);
	}
	
	public function addIsPasswordChangedCheckbox() 
	{
		$checkbox = $this->createElement('checkbox', 'isPasswordChanged');
		$checkbox->setLabel('Đổi mật khẩu');
		$checkbox->setDecorators(array(
			array('ViewHelper', array('class' => 'span-1 roleCheckBox')),
			array('Label', array('placement' => 'APPEND', 'class' => 'span-5 roleLabel')),
			array('HtmlTag', array('tag' => 'div',
								   'class' => 'span-6 roleDiv'
			))
		));
		$checkbox->setOrder(2);
		$this->getDisplayGroup('userGroup')->addElement($checkbox);
	}
	
	private function _createSubmitButton()
	{
		$submit = $this->createElement('submit', 'submit');
		$submit->setLabel('Chấp nhận');		
		$submit->setDecorators($this->_submitDecorators);
		$submit->getDecorator('HtmlTag')->setOption('id', 'createUserButton');
		$submit->setAttribs(array(
			'class' => 'span-4 last submitDecorator',
		));
		return $submit;
	}
	
	private function _createPasswordConfirmElement()
	{
		$passwordNotEmptyValidator = $this->_createNotEmptyValidator('Làm ơn nhập mật khẩu');
		$passwordStringLengthValidator = $this->_createStringLengthValidator(3, 40, 
									  'Mật khẩu quá ngắn. Mật khẩu phải có ít nhất %min% chữ số',
									  'Mật khẩu quá dài. Mật khẩu chỉ được có nhiều nhất là %max% chữ số');
		$passwordConfirm = $this->createElement('password', 'password_confirm')
								->setLabel('Nhập lại mật khẩu')
						 	    ->setAutoInsertNotEmptyValidator(false)
								->setRequired(true)
								->setFilters(array('StringTrim'));
		$passwordConfirm->setValidators(array(array($passwordNotEmptyValidator, true),
										      array($passwordStringLengthValidator, true),
										      array('PasswordConfirmation', true)));
		$passwordConfirm->setAttribs(array(
			'class' => 'column span-6 last',
		));
		$passwordConfirm->getDecorator('Label')->setOption('class', 'column span-4 labelDecorator');
		$passwordConfirm->getDecorator('Errors')->setOption('class', 'span-6 errorDecorator');
		return $passwordConfirm;
	}
	
	private function _createPasswordElement()
	{
		$passwordNotEmptyValidator = $this->_createNotEmptyValidator('Làm ơn nhập mật khẩu');
		$passwordStringLengthValidator = $this->_createStringLengthValidator(3, 40, 
									  'Mật khẩu quá ngắn. Mật khẩu phải có ít nhất %min% chữ số',
									  'Mật khẩu quá dài. Mật khẩu chỉ được có nhiều nhất là %max% chữ số');		
		$password = $this->createElement ( 'password', 'password' )
						 ->setLabel ( 'Mật khẩu: ' )
						 ->setAutoInsertNotEmptyValidator(false)
						 ->setRequired ( true )
						 ->setFilters(array('StringTrim'))
						 ->setValidators(array(array($passwordNotEmptyValidator, true),
						   			           array($passwordStringLengthValidator, true)));
		$password->setAttribs(array(
			'class' => 'column span-6 last',
		));
		$password->getDecorator('Label')->setOption('class', 'column span-4 labelDecorator');
		$password->getDecorator('Errors')->setOption('class', 'span-6 errorDecorator');
		return $password;
	}
	
	private function _createUsernameElement()
	{
		$usernameNotEmptyValidator = $this->_createNotEmptyValidator('Làm ơn nhập tên đăng nhập');
		$uniqueUsernameValidator = new TBB_Validate_UniqueUsername(new Admin_Model_Users());
		$username = $this->createElement ( 'text', 'newUsername' )
						 ->setLabel ( 'Tên đăng nhập: ' )
						 ->setAutoInsertNotEmptyValidator(false)
						 ->setRequired ( true )
						 ->addFilter ( 'StripTags' )
						 ->setValidators(array(array($usernameNotEmptyValidator, true),
						 					   array($uniqueUsernameValidator, true)
						 					   ));
		$username->setAttribs(array(
			'class' => 'column span-6 last'
		));	
		$username->getDecorator('Label')->setOption('class', 'column span-4 labelDecorator');
		$username->getDecorator('Errors')->setOption('class', 'span-6 errorDecorator');
		return $username;
	}
	
	public function disableUsernameInput()
	{
		$this->getElement('newUsername')->setAttrib('readonly', 'readonly');
	}
	
	private function _createUserIDElement()
	{
		$id = $this->createElement ( 'hidden', 'user_id' );
		$id->setDecorators ( $this->_hiddenDecorators );
		$id->setAttribs(array(
			'class' => 'span-4',
		));
		return $id;
	}	
	
	public function addRoleCheckboxes($userID = null)	{
		///////////////////// create role checkboxes /////////////////////
		// get role array
		$roleModel = new Admin_Model_Role();
		$roleArray = $roleModel->getRoleArray();

		// create subform
		$subForm = new Zend_Form_SubForm(array('class' => 'roleGroup'));	
		$subForm->setDecorators($this->_displayGroupDecorators);
		$subForm->setOptions(array('class' => 'fieldsetForm span-7'));
		
		// this case is for updating user
		if($userID) {
			$checkboxes = $this->_createCheckboxesForUpdatingUser($userID);			
		}	
		// this case is for creating user
		else {
			$checkboxes = $this->_createCheckboxesForCreatingUser();
		
		}
		$subForm->addElements($checkboxes);
		$this->addSubForm($subForm, 'roles');
	}
	
	/**
	 * Create checkboxes for creating user
	 * @return array
	 */
	private function _createCheckboxesForCreatingUser() {
		$roleCheckboxes = array();
		
		// get role array
		$roleModel = new Admin_Model_Role();
		$roleArray = $roleModel->getRoleArray();
		
		// get customer role ID
		$customerRoleID = $roleModel->getCustomerRoleID();
		
		// create role checkboxes
		foreach($roleArray as $index => $role) {
			$roleCheckbox = $this->createElement('checkbox', (string)$role['role_id']);
			
			// check if the role is customer
			if($role['role_id'] == $customerRoleID) {
				$roleCheckbox->setAttrib('disabled', 'disabled');
			}
			
			$roleCheckbox->setLabel($role['role_name']);
			$this->_customizeRoleCheckBox($roleCheckbox);
			$roleCheckboxes[] = $roleCheckbox;
		}		
		return $roleCheckboxes;
	}
	
	/**
	 * Create checkboxes for updating user
	 * @param int $userID
	 * @return array
	 */
	private function _createCheckboxesForUpdatingUser($userID) {
		$roleCheckboxes = array();
		
		// get role array
		$roleModel = new Admin_Model_Role();
		$roleArray = $roleModel->getRoleArray();
		
		// get customer role ID
		$customerRoleID = $roleModel->getCustomerRoleID();		
		
		// get roles of the user
		$userModel = new Admin_Model_Users();
		$rolesOfUser = $userModel->getRolesOfUser($userID);
		
		// extract role_id of $roleOfUser array
		$roleIDs = array();		
		foreach($rolesOfUser as $role) {
			$roleIDs[] = $role['role_id'];
		}

		// create role checkboxes
		foreach($roleArray as $index => $role) {
			if(in_array($role['role_id'], $roleIDs)) {
				$roleCheckbox = $this->createElement('checkbox',
										 (string)$role['role_id'], array('checked' => 'checked'));				
			} else {
				$roleCheckbox = $this->createElement('checkbox',
										 (string)$role['role_id'], array());				
			}
			
			// check if the role is customer
			if($role['role_id'] == $customerRoleID) {
				$roleCheckbox->setAttrib('disabled', 'disabled');
			}

			$roleCheckbox->setLabel($role['role_name']);
			$this->_customizeRoleCheckBox($roleCheckbox);															 
			$roleCheckboxes[] = $roleCheckbox;
		}
		return $roleCheckboxes;
	}
	
	private function _customizeRoleCheckBox($roleCheckbox)
	{		
		$roleCheckbox->setDecorators(array(
			array('ViewHelper', array('class' => 'span-1 roleCheckBox')),
			array('Label', array('placement' => 'APPEND', 'class' => 'span-5 roleLabel')),
			array('HtmlTag', array('tag' => 'div',
								   'class' => 'span-6 roleDiv'
			))
		));		
	}
}